



let EventEmitter = require('eventemitter3');
let mixins = require('../utils/mixins');

const templateDiv = `
    <span id="name"></span>
    x:<input type="number" class="p3" id="x">
    y:<input type="number" class="p3" id="y">
    z:<input type="number" class="p3" id="z">
`;

const EventName = {
    X:'x',
    Y:'y',
    Z:'z',
};

const DefaultOption = {
    x : 0,
    y : 0,
    z : 0,
    step : 0.1,
    name:''
};


class P3 {
    constructor(options = {}){

        mixins(options,DefaultOption);
        let x = options.x;
        let y = options.y;
        let z = options.z;
        let step = options.step;
        let name = options.name;

        // data
        this._x = this._y = this._z = 0;

        this.element = globalThis.document.createElement('div');
        this.element.innerHTML = templateDiv;

        this.nameEl= this.element.querySelector('#name');
        this.nameEl.innerText = name;

        this.xEl = this.element.querySelector('#x');
        this.yEl = this.element.querySelector('#y');
        this.zEl = this.element.querySelector('#z');

        // 添加step
        this.xEl.setAttribute('step',step);
        this.yEl.setAttribute('step',step);
        this.zEl.setAttribute('step',step);

        // 绑定
        this.xEl.addEventListener('change',this.onXUIChange.bind(this),false);
        this.yEl.addEventListener('change',this.onYUIChange.bind(this),false);
        this.zEl.addEventListener('change',this.onZUIChange.bind(this),false);

        this.ee = new EventEmitter();
        this.ee.on(EventName.X,this.onXDataChange,this);
        this.ee.on(EventName.Y,this.onYDataChange,this);
        this.ee.on(EventName.Z,this.onZDataChange,this);

        this.setX(x);
        this.setY(y);
        this.setZ(z);
    }

    // data->ui
    onXDataChange(newValue){
        this.xEl.value = newValue;
    }
    onYDataChange(newValue){
        this.yEl.value = newValue;
    }
    onZDataChange(newValue){
        this.zEl.value = newValue;
    }

    // set
    setX(newValue){
        this._x = newValue;
        this.ee.emit(EventName.X,this._x);
    }

    setY(newValue){
        this._y = newValue;
        this.ee.emit(EventName.Y,this._y);
    }

    setZ(newValue){
        this._z = newValue;
        this.ee.emit(EventName.Z,this._z);
    }

    // ui->data
    onXUIChange(){
        this.setX(parseFloat(this.xEl.value));
        console.log('x:',this._x);
    }

    onYUIChange(){
        this.setY(parseFloat(this.yEl.value));
        console.log('y:',this._y);
    }
    onZUIChange(){
        this.setZ(parseFloat(this.zEl.value));
        console.log('z:',this._z);
    }

    getX(){return this._x;}
    getY(){return this._y;}
    getZ(){return this._z;}
}

module.exports = P3;
